
import React, { useEffect, useState } from "react";
import AudioCanvas from "@/components/AudioCanvas/AudioCanvas";
import ContentCard from "@/components/ContentCard/ContentCard";
import styled from 'styled-components';
import LineCharts, { IChartData } from "@/components/LineCharts/LineCharts";
import { getSchummanData } from '@/apis/apis'
import { readExcel, solveSpecificStr } from '@/util/util'


const FlexRow = styled.div`
    display: flex;
    flex-direction: row;
    flex-wrap: no-wrap;
    justify-content: space-between;
    align-items: center;
    -webkit-align-items: none;
`;

const FlexColumn = styled.div`
    position: relative;
    width: calc(100% - 500px - 16px);
    display: flex;
    flex-direction: column;
    flex-wrap: no-wrap;
    justify-content: center;
`;

interface IProps {
    area?: string;
}

const Schumann = (props: IProps) => {

    const { area } = props;

    const [ imgUrl, setImgUrl ] = useState<string>('');
    const [ frequencies, setFrequencies ] = useState<number[][]>([[], [], []]);
    
    const [ ann, setAnn ] = useState<number[]>([]);
    const [ det, setDet ] = useState<IChartData[]>([]);
    const [ order, setOrder ] = useState<IChartData[]>([]);
    const [ trace, setTrace ] = useState<IChartData[]>([]);

    // Audio list
    const [ playList, setPlayList ] = useState<string[]>([]);

    const characteristicType = [ "det", "order", "trace" ];
    const characteristicMap = {
        dt: '一阶时间差分',
        d2t: '二阶时间差分',
        df: '一阶频率差分',
        d2f: '二阶频率差分',
        img: '映射矩阵',
        fx1: '一阶映射导数矩阵',
        fx2: '二阶映射导数矩阵',
    };

    const optionCommon = {
        type: 'line',
        smooth: true,
        showSymbol: false,
        areaStyle: {
            opacity: 0.1
        },
    }
    const optionAnn = [
        {
            name: 'A(n, N=5)',
            data: ann,
            ...optionCommon
        },
    ]
    const option = [
        {
            name: '一阶',
            data: frequencies[0],
            ...optionCommon
        },
        {
            name: '二阶',
            data: frequencies[1],
            ...optionCommon,
        },
        {
            name: '三阶',
            data: frequencies[2],
            ...optionCommon,
        },
    ]

    const fetchSchummanData = async () => {

        const { url }: IResourceURL = await getSchummanData({
            time: '20230621',
            type: "ALL"
        });

        const [
            autoEncoderData,
            frequencyData,
            annData,
        ]: Record<string, number>[][] = await Promise.all([
            readExcel(url.AUTOENCODER),
            readExcel(url.FREQUENCY),
            readExcel(url.ANN),
        ]);
        
        setImgUrl(url.ORIGIN_IMAGE);
        setPlayList([url.ORIGIN_AUDIO]);
        setFrequencies(frequencyData.reduce((pre, cur) => {
            pre[0].push(cur.Rank1)
            pre[1].push(cur.Rank2)
            pre[2].push(cur.Rank3)
            return pre
        }, [[], [], []] as number[][]));
        setAnn(annData.map((item) => item.Rank1));
        
        const characteristicRecord: Record<string, any[]>= {};
        const keyMap = autoEncoderData.reduce((prev: Record<string, (string | number)[]>, cur) => {
            Object.keys(cur).forEach((key) => {
                if (Array.isArray(prev[key])) {
                    prev[key].push(cur[key])
                } else prev[key] = [cur[key]];
            })
            return prev
        }, {});
        
        Object.keys(characteristicMap).forEach((keyName) => {
            characteristicType.forEach((keyType) => {
                if (keyType === 'det') {
                    /** 行列式由于是字符串，需要特殊处理 */
                    keyMap[`${keyName}_${keyType}`] = keyMap[`${keyName}_${keyType}`].map((detStr) => {
                        if (typeof detStr === 'string') {
                            const [ [real], [imag] ] = solveSpecificStr(detStr);
                            return Math.floor(Math.sqrt(Math.pow(real, 2) + Math.pow(imag, 2)))
                        } else return detStr
                    })
                }
                if (Array.isArray(characteristicRecord[keyType])) {
                    characteristicRecord[keyType].push({
                        name: characteristicMap[keyName],
                        data: keyMap[`${keyName}_${keyType}`],
                        ...optionCommon
                    })
                } else {
                    characteristicRecord[keyType] = [{
                        name: characteristicMap[keyName],
                        data: keyMap[`${keyName}_${keyType}`],
                        ...optionCommon
                    }]
                }
            })
        })
        setDet(characteristicRecord.det);
        setOrder(characteristicRecord.order);
        setTrace(characteristicRecord.trace);
    }

    useEffect(() => {
        fetchSchummanData();
    }, [])


    return (
        <>
            <FlexRow style={{ width: '100%' }}>
                <ContentCard
                    style={{ width: '500px', height: '500px', marginRight: '16px' }}
                    title="时频图像"
                    tooltip={{
                        show: true,
                        content: "此处展示的是数据图像。默认展示上三天的数据。",
                    }}
                >
                    <img style={{ width: '100%', height: '100%' }} src={imgUrl}></img>
                </ContentCard>
                <FlexColumn style={{ height: '500px' }}>
                    <ContentCard
                        style={{ height: '230px' }}
                        title="采集音频"
                        tooltip={{
                            show: true,
                            content: "此处展示的是数据音频, 点击播放按钮可进行播放。默认展示30分钟前的数据。",
                        }}
                    >
                        <AudioCanvas playList={playList}/>
                    </ContentCard>
                    <ContentCard
                        style={{ height: 'calc(500px - 230px - 16px)' }}
                        title="前三阶舒曼谐振频率曲线"
                        tooltip={{
                            show: true,
                            content: "此处展示的是数据图像。默认展示上三天的数据。",
                        }}
                    >
                        <LineCharts id="frequency" area={area} style={{ height: '100%' }} data={option}/>
                    </ContentCard>
                </FlexColumn>
            </FlexRow>
            <FlexRow style={{ width: '100%' }}>
                <ContentCard
                    title="一阶异常数 A(n, N=5)"
                    tooltip={{
                        show: true,
                        content: "此处展示的是数据图像。默认展示上三天的数据。",
                    }}
                >
                    <LineCharts area={area} id="ann" data={optionAnn}/>
                </ContentCard>
            </FlexRow>
            <FlexRow style={{ width: '100%' }}>
                <ContentCard
                    id="det"
                    style={{ width: '100%' }}
                    title="指标行列式"
                    tooltip={{
                        show: true,
                        content: "此处展示的是数据曲线。默认展示前60天的数据。",
                    }}
                >
                    <LineCharts area={area} id="det" data={det}/>
                </ContentCard>
            </FlexRow>
            <FlexRow style={{ width: '100%' }}>
                <ContentCard
                    id="order"
                    style={{ width: '100%' }}
                    title="指标秩"
                    tooltip={{
                        show: true,
                        content: "此处展示的是数据曲线。默认展示前60天的数据。",
                    }}
                >
                    <LineCharts area={area} id={'order'} data={order}/>
                </ContentCard>
            </FlexRow>
            <FlexRow style={{ width: '100%' }}>
                <ContentCard
                    id="trace"
                    style={{ width: '100%' }}
                    title="指标迹"
                    tooltip={{
                        show: true,
                        content: "此处展示的是数据曲线。默认展示前60天的数据。",
                    }}
                >
                    <LineCharts area={area} id="trace" data={trace}/>
                </ContentCard>
            </FlexRow>
        </>
    )
};

export default Schumann;